<template>
    <div>
        <Category @getCategoryId="handleCategoryChange"></Category>
        <el-card shadow="always" :body-style="{ padding: '20px' }" style="margin-top: 10px;">
            <div v-show="isShowList">
                <el-button type="primary" size="default" icon="el-icon-plus" :disabled="!category3Id" @click="showAdd">
                    添加</el-button>
                <el-table border stripe style="margin-top: 10px;" :data="attrs">
                    <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                    <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
                    <el-table-column label="属性列表">
                        <template slot-scope="{row, $index}">
                            <el-tag type="info" v-for="value in row.attrValueList" :key="value.id"
                                style="margin:0px 3px" :type="value.id % 2 == '0' ? 'success' : 'warning'">{{
                                        value.valueName
                                }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="120px">
                        <template slot-scope="{row, $index}">
                            <el-button type="primary" size="small " title="修改" icon="el-icon-edit"
                                @click="handlerUpdate(row)"></el-button>
                            <el-button type="danger" size="small " title="删除" icon="el-icon-delete"
                                @click="handlerDelete(row)"></el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div v-show="!isShowList">
                <el-form inline ref="form" :model="attr">
                    <el-form-item label="属性名">
                        <el-input placeholder="请输入属性值" v-model="attr.attrName"></el-input>
                    </el-form-item>
                </el-form>
                <el-button type="primary" size="default" @click="handlerAbility" icon="el-icon-plus"
                    :disabled="!attr.attrName">添加属性值</el-button>
                <el-button @click="isShowList = true">取消</el-button>
                <el-table border stripe style="margin: 10px 0;" :data="attr.attrValueList">
                    <el-table-column label="序号" type="index" width="80px" align="center"></el-table-column>
                    <el-table-column label="属性值名称">
                        <template slot-scope="{row,$index}">
                            <el-input :ref="$index" v-if="row.edit" @blur="toLook(row)" v-model="row.valueName"
                                placeholder="请输入名称" size="mini" @keyup.native.enter="toLook(row)" />
                            <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template slot-scope="{row,$index}">
                            <el-popconfirm :title="`确定要删除${row.valueName}吗？`"
                                @confirm="attr.attrValueList.splice($index, 1)">
                                <el-button slot="reference" icon="el-icon-delete" type="danger" size="small ">删除
                                </el-button>
                            </el-popconfirm>
                        </template>
                    </el-table-column>
                </el-table>
                <el-button type="primary" :disabled="!attr.attrName || attr.attrValueList.length === 0" @click="save">保存
                </el-button>
                <el-button @click="isShowList = true">取消</el-button>

            </div>
        </el-card>
    </div>
</template>

<script>

import { reqAttrData, reqAddOrUpdateAttr, reqDelete } from '@/api/product/attr';
import cloneDeep from 'lodash/cloneDeep'
export default {
    data() {
        return {
            category1Id: null, // 一级分类ID
            category2Id: null, // 二级分类ID
            category3Id: null, // 三级分类ID
            attrs: [], // 属性列表
            isShowList: true,//是否显示属性列表界面，如果是false显示添加或者修改界面
            attr: {
                attrName: '', // 属性名
                attrValueList: [], // 属性值列表
                categoryId: '', // 当前第3级分类ID
                categoryLevel: 3, // 分类级别
            }, // 当前要操作的属性对象
        }
    },
    methods: {
        handleCategoryChange({ categoryId, level }) {
            console.log(categoryId);
            if (level === 1) {
                //重置二级与三级分类的数据
                this.category2Id = null
                this.category3Id = null
                this.attrs = []
                this.category1Id = categoryId
            } else if (level === 2) {
                //重置三级分类的数据
                this.category3Id = null
                this.attrs = [] //重置属性列表
                this.category2Id = categoryId
            } else {
                this.category1Id = categoryId.category1Id
                this.category2Id = categoryId.category2Id
                this.category3Id = categoryId.category3Id
                //只有当选择了三级分类，才请求获取属性列表
                this.getAttrs()
            }
        },
        // 获取属性列表
        async getAttrs() {
            const { category1Id, category2Id, category3Id } = this
            const result = await reqAttrData(category1Id, category2Id, category3Id)
            this.attrs = result.data
        },
        //添加按钮
        showAdd() {
            this.isShowList = false
            this.attr = {
                attrName: '',//属性名
                attrValueList: [],
                categoryId: this.category3Id,
                categoryLevel: 3
            }
        },
        //当input框失去焦点的时候变为查看模式
        toLook(row) {
            //如果输入的数据是空的，还是编辑模式
            if (row.valueName.trim() === '') return
            const isRepeat = this.attr.attrValueList
                .filter(value => value.valueName === row.valueName).length === 2
            if (isRepeat) {
                this.$message.warning('属性名称不能重复')
                row.valueName = ''
                return
            }
            row.edit = false
        },
        toEdit(row) {
            if (row.hasOwnProperty('edit')) {
                row.edit = true

            } else {
                this.$set(row, 'edit', true)
            }
        },
        // 添加新的平台属性值
        handlerAbility() {
            const attrValue = {
                attrId: this.attr.id, //当前要修改的属性id
                valueName: '', //属性值名称
                edit: true //标识为编辑模式
            }
            this.attr.attrValueList.push(attrValue)
            //让最后一个输入框自动获取焦点
            this.$nextTick(() => this.$refs[this.attr.attrValueList.length - 1].focus())
        },
        //保存按钮
        async save() {
            console.log(1111);
            const { attr } = this
            attr.attrValueList = attr.attrValueList.filter(attrValue => {
                if (attrValue.valueName) {
                    //删除attrValue对象中的edit属性
                    delete attrValue.edit
                    return true
                }
                return false
            })
            if (attr.attrValueList.length === 0) {
                this.$message.warning('至少指定一个属性值名称')
                return
            }
            try {
                //发添加或更新的请求
                const result = await reqAddOrUpdateAttr(attr)
                this.$message.success('保存属性成功')
                //显示列表
                this.isShowList = true
                //重新获取属性列表
                this.getAttrs()
            } catch (error) {

            }
        },
        // 修改回调
        handlerUpdate(row) {
            this.isShowList = false
            this.attr = cloneDeep(row)

        },
        //删除回调
        async handlerDelete(row) {
            console.log(row);
            const result = await reqDelete(row.id)
            this.$message.success(result.message || '删除属性成功')
            this.getAttrs()
        }
    },
}
</script>

<style lang="scss" scoped>

</style>